package utils
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class AnimationPlayer
	{
		private var _animation:Vector.<BitmapAnimation> = new Vector.<BitmapAnimation>();
		//private var _ani:BitmapAnimation;
		private var _timer:Timer;
		private var _fps:int;
		public function AnimationPlayer(ani:BitmapAnimation=null,fps:Number = 24)
		{
			//_ani = ani;
			if(ani){
				_animation.push(ani);
			}
			_fps=fps;
		}
		
		private function onTimer(e:TimerEvent):void
		{
			for (var i:int = 0; _animation!=null && i < _animation.length; i++) 
			{
				_animation[i].reader(); 
			}
		}
		public function push(bitmapAnimation:BitmapAnimation):void{
			if(_animation==null) _animation=new Vector.<BitmapAnimation>();
			_animation.push(bitmapAnimation);
		}
		public function remove(aniamtion:BitmapAnimation):void{
		   var index:int=_animation.indexOf(aniamtion);
		   if(index>=0){
		       _animation.splice(index,1);
			   if(_animation.length==0){
				   dispose();
			   }   
		   } 
		}
		public function play():void
		{
			if(_timer == null){	
				_timer = new Timer(1000/_fps);
				_timer.addEventListener(TimerEvent.TIMER,onTimer,false,0,true);
			}
			_timer.start();
		}
		
		public function stop():void
		{
			if(_timer == null)	return;
			_timer.stop();
		}
		
		public function dispose():void
		{
			if(_timer != null)
			{
				if(_timer.hasEventListener(TimerEvent.TIMER))
					_timer.removeEventListener(TimerEvent.TIMER,onTimer);
				_timer.stop();
				_timer = null;
			}
			_animation = null;
		}		
	}
}